package com.zmj.commoncore.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by: meijun
 * Date: 2018/10/20 21:42
 */
@Slf4j
public class JWTUtil {

    public static String secret = "Jj3(JK@MFSl22%JJ01lm";

    /** token 过期时间: 10天 */
    public static final int calendarField = Calendar.SECOND;
    public static final int calendarInterval = 60 * 60 * 24 * 7;

    public static String createToken(String userId){
        Date iatDate = new Date();

        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();


        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}

        try {
            String token = JWT.create().withHeader(map) // header
                    .withClaim("author", "zmjmall") // payload
                    .withClaim("source", "mobile").withClaim("userid", null == userId ? null : userId)
                    .withIssuedAt(iatDate) // sign time
                    .withExpiresAt(expiresDate) // expire time
                    .sign(Algorithm.HMAC256(secret)); // signature
            return token;

        }catch (Exception e) {
            e.printStackTrace();
            log.error("[token] 创建token出现异常 .");
        }

        return null;
    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
             e.printStackTrace();
            log.error("[token] verifyToken 验证非法");
        }
        return jwt.getClaims();
    }

    /**
     * 根据Token获取user_id
     *
     * @param token
     * @return user_id
     */
    public static String getAppUID(String token){

        Map<String, Claim> claims = verifyToken(token);
        Claim user_id_claim = claims.get("userid");
        if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
            log.error("[token] getAppUID 验证非法");
            return null;
        }
        return user_id_claim.asString();
    }

}
